<template>
    <entity-view
      :operator-type="operatorType"
      :model="beanInfo"
      @submit="submit"
      :rules="rules"
      ref="form"
    >
      <div class="subtitle">基本信息</div>
      <div class="sub-content-flex">
        <form-item label="产品编码" v-model="beanInfo.baseProdCode" prop="baseProdCode" disabled></form-item>
        <form-item label="产品名称" v-model="beanInfo.baseProdName" prop="baseProdName" disabled></form-item>
        <form-item label="产品描述" v-model="beanInfo.baseProdDesc" prop="baseProdDesc" disabled></form-item>
        <form-item label="产品属性" v-model="beanInfo.prodDefaultFlag" prop="prodDefaultFlag" input-type="select" :options="[
          {name: '线下产品', value: '00'},
          {name: '线上产品', value: '01'},
        ]" disabled></form-item>
        <form-item
          v-if="beanInfo.baseProdCode === '02' || beanInfo.baseProdCode === '03' || beanInfo.baseProdCode === '07'"
          label="微信支付通道编码" v-model="beanInfo.wechatChannelId" prop="wechatChannelId" :options="wxPaymentChannels"
          options-value="id" input-type="select"></form-item>
        <form-item
          v-if="beanInfo.baseProdCode === '02' || beanInfo.baseProdCode === '03' || beanInfo.baseProdCode === '08'"
          label="支付宝支付通道编码" v-model="beanInfo.alipayChannelId" prop="alipayChannelId" :options="aliPaymentChannels"
          options-value="id" input-type="select"></form-item>
      </div>
      <template v-if="beanInfo.baseProdCode !== '04'">
        <div class="subtitle">费率信息</div>
        <div class="sub-content-block">
          <a-table :columns="feeRateColumns" :dataSource="feeInfoList" rowKey="id" :pagination="false">
            <template slot="feeInputMode" slot-scope="text, record">
              <a-select v-model="record.feeInputMode" :disabled="operatorType !== 'edit'">
                <a-select-option value="1">手工输入按比率</a-select-option>
                <a-select-option value="2">手工输入按固定金额</a-select-option>
                <a-select-option value="3">手工输入按比率+封顶值</a-select-option>
              </a-select>
            </template>
            <template slot="feeRate" slot-scope="text, record">
              <a-input type="number" v-model="record.feeRate" :disabled="record.feeInputMode === '2' || operatorType !== 'edit'" min="0"></a-input>
            </template>
            <template slot="feeCappingAmt" slot-scope="text, record">
              <a-input type="number" v-model="record.feeCappingAmt" disabled
                       v-if="record.feeInputMode == '1'" min="0" oninput="this.value = this.value.replace(/[^0-9]/g,'')"></a-input>
              <a-input type="number" v-model="record.feeFixedAmt" :disabled="record.feeInputMode === '1' || operatorType !== 'edit'"
                       v-if="record.feeInputMode == '2'" min="0" oninput="this.value = this.value.replace(/[^0-9]/g,'')"></a-input>
              <a-input type="number" v-model="record.feeCappingAmt" :disabled="record.feeInputMode === '1' || operatorType !== 'edit'"
                       v-if="record.feeInputMode == '3'" min="0"  oninput="this.value = this.value.replace(/[^0-9]/g,'')"></a-input>
            </template>
          </a-table>
        </div>
      </template>
      <div class="subtitle">交易权限信息</div>
      <div class="sub-content-block">
        <a-form-model-item label="交易大类" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
          <a-checkbox-group :options="txnGroup" v-model="selectedTxnGroup" @change="checkAllChange"  :disabled="operatorType !== 'edit'"></a-checkbox-group>
        </a-form-model-item>
        <a-form-model-item
          :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }"
          :label="i.txnGroupName" v-for="i in txnGroup" :key="i.value"
                           v-if="selectedTxnGroup.includes(i.txnGroup)">
          <a-checkbox-group  :options="i.pTxnAuthMaps" v-model="i.selectedTxnGroup"  :disabled="operatorType !== 'edit'"
                            @change="checkboxChange($event, i)"></a-checkbox-group>
        </a-form-model-item>
      </div>
      <template v-if="beanInfo.baseProdCode === '04'">
        <div class="subtitle">分期产品信息</div>
        <div class="sub-content-block">
          <div class="btn-group" v-if="this.operatorType === 'add' || this.operatorType ==='edit'">
            <a-button type="primary" icon="plus" @click="stageAdd()">新增</a-button>
          </div>
          <a-table :columns="stageColumns" :dataSource="stageList" rowKey="id" :pagination="false">
            <template slot="operation" slot-scope="text, record, index">
              <a-icon type="setting" theme="twoTone" twoToneColor="#4a9ff5" @click="stageEdit(record,index)" title="修改" ></a-icon>
              <a-icon type="delete" theme="twoTone" twoToneColor="#4a9ff5" @click="stageDel(record,index)"  title="删除" ></a-icon>
            </template>
          </a-table>
        </div>
      </template>
      <installment-product ref="modalForm" @submit="stageSubmit" modal-name="分期产品" ></installment-product>
    </entity-view>
</template>
<script>
import EntityView from '../../../../components/common/entityView/EntityView.vue'
import FormItem from '../../../../components/common/entityView/FormItem.vue'
import InstallmentProduct from './InstallmentProduct.vue'
export default {
  name: 'BaseProductsOperation',
  inject: ['baseProductContext'],
  components: {
    EntityView,
    FormItem,
    InstallmentProduct
  },

  data: function () {
    return {
      modalVisible: false,
      modalTitle: '',
      operatorType: 'add',
      beanInfo: {
        baseProdCode: '',
        baseProdName: '',
        baseProdDesc: '',
        prodDefaultFlag: '',
        wechatChannelId: '',
        alipayChannelId: '',
      },
      feeInfoList: [],
      txnGroup: [], // 获取的交易权限组组
      selectedTxnGroup: [], // 选中的交易权限组
      rules: {
        wctUpNo: [{required: true, message: '请输入上级类目代码', trigger: 'blur'}],
        wctSecNo: [{required: true, message: '请输入二级类目代码', trigger: 'blur'}],
        wctSecName: [{required: true, message: '请输入二级类目描述', trigger: 'blur'}],
      },
      selectOptions: [],
      loading: false,

      feeRateColumns: [
        {
          title: '卡种/业务',
          dataIndex: 'remark1'
        },
        {
          title: '费率输入方式',
          dataIndex: 'feeInputMode',
          scopedSlots: {customRender: 'feeInputMode'}
        },
        {
          title: '费率比率(‰)',
          dataIndex: 'feeRate',
          scopedSlots: {customRender: 'feeRate'}
        },
        {
          title: '封顶值(元)/固定金额(元)',
          dataIndex: 'feeCappingAmt',
          scopedSlots: {customRender: 'feeCappingAmt'}
        }
      ],
      stageColumns: [
        {
          title: "分期产品代码",
          dataIndex: "prodStageCode",
        },
        {
          title: "分期产品名称",
          dataIndex: "prodStageName",
        },
        {
          title: "分期期数",
          dataIndex: "prodStageNum",
        },
        {
          title: "操作",
          scopedSlots: {customRender: 'operation'}
        },
      ],
      stageList: [],
      wxPaymentChannels: [],
      aliPaymentChannels: [],
      okText: '确定'
    }
  },
  methods: {

    async submit() {
      let res
      switch (this.operatorType) {
        case 'start':
          res = await this.edit("use")
          break
        case 'stop':
          res = await this.edit("stop")
          break
        case 'edit':
          res = await this.edit("upd")
          break
        case 'view':
          res = true
          break
        default:
          break
      }
      return res
    },
    async edit(optFlag) {
      const res = await this.$refs.form.validate()
      if (res) {
        const map = {};
        this.txnGroup.map(item => {
          map[item.txnGroup] = item
        })
        const authCtrlList = []
        this.selectedTxnGroup.map(val => {
          const item = map[val];
          authCtrlList.push(...item.pTxnAuthMaps.filter(n => {
            if (item.selectedTxnGroup.indexOf(n.value) > -1) {
              n.instId = this.beanInfo.instId
              n.prodType= '00'
              n.baseProdCode= this.beanInfo.baseProdCode
              n.optFlag= optFlag
              return true
            }
          }))
        })

        const params = Object.assign({}, this.beanInfo, {
          optFlag: optFlag,
          bProdAuthCtrlList: authCtrlList,
          bProdStageList: this.stageList,
          bProdFeeList: this.feeInfoList
        })
        const res = await this.$put('/admin/mcmp/bBaseProdInfo/update', params)
        if (res.status === 200) {
          this.$message.success('保存成功！')
          return true
        } else {
          this.$message.error(res.data.message)
          return false
        }
      }
    },
    resetFields() {
      return this.$refs.form.resetFields()
    },
    setOperatorType(type) {
      this.operatorType = type
    },
    async setBeanInfo(beanInfo) {
      this.beanInfo = beanInfo;
      this.getOne();
      if(this.beanInfo.baseProdCode === '02' || this.beanInfo.baseProdCode === '03' || this.beanInfo.baseProdCode === '07'){
        this.wxPaymentChannels = await this.getPaymentChannel('UPWX')
      }
      if(this.beanInfo.baseProdCode === '02' || this.beanInfo.baseProdCode === '03' || this.beanInfo.baseProdCode === '08'){
        this.aliPaymentChannels = await this.getPaymentChannel('UPAL')
      }
    },
    async getOne() {
      try {
        const res = await this.$get('/admin/mcmp/bBaseProdInfo/edit', {
          baseProdCode: this.beanInfo.baseProdCode,
          instId: this.beanInfo.instId
        })
        this.beanInfo = res.data.entity || {}
        this.feeInfoList = res.data.feeInfos || {}
        this.selectedTxnGroup = []
        this.txnGroup = (res.data.pTxnGroups || []).map(i => {
          i.label = i.txnGroupName;
          i.value = i.txnGroup
          if (i.isChecked === '1') {
            this.selectedTxnGroup = [...this.selectedTxnGroup, i.txnGroup]
          }
          if (i.pTxnAuthMaps) {
            i.selectedTxnGroup = []
            i.pTxnAuthMaps = i.pTxnAuthMaps.map(item => {
              item.label = item.txnName;
              item.value = item.txnNum.concat("|").concat(item.bizType)
              item.isChecked === '1' && i.selectedTxnGroup.push(item.value)
              return item
            })
            i.checkAll = i.selectedTxnGroup.length === i.pTxnAuthMaps.length
            i.indeterminate = !!i.selectedTxnGroup.length && i.selectedTxnGroup.length < i.pTxnAuthMaps.length
          }
          return i
        })
        this.stageList = res.data.stageInfos
      } catch (e) {
        console.error(e)
      }
    },
    async getPaymentChannel(type) {
      try {
        const query = encodeURIComponent('&' + this.baseProductContext.query.instId + '&' + type)
        const res = await this.$get('/admin/igas/pDstChannelCfg/select2List?q=' + query)
        return res.data.map(i=>{
          i.value = i.id
          i.name = i.id + "-" + i.name
          return i;
        })
      } catch (e) {
        console.error(e)
      }
    },
    checkboxChange(e, item) {
      item.indeterminate = !!item.selectedTxnGroup.length && item.selectedTxnGroup.length < item.pTxnAuthMaps.length
      if (item.selectedTxnGroup.length === 0) {
        this.selectedTxnGroup.splice(this.selectedTxnGroup.indexOf(item.txnGroup), 1)
      }
    },
    checkAllChange() {
      this.txnGroup.map((item, index) => {
        item.indeterminate = false
        const checked = this.selectedTxnGroup.indexOf(item.value) > -1
        item.selectedTxnGroup = checked ? item.pTxnAuthMaps.map(i => i.txnNum.concat("|").concat(i.bizType)) : []
        this.$set(this.txnGroup, index, item)
      })
    },
    stageEdit(record,index){
      this.$nextTick(() => {
        this.$refs.modalForm.visible = true;
        this.$refs.modalForm.setBeanInfo('edit',record,index);
      });
    },
    stageDel(record,index){
      this.stageList.splice(index,1)
    },
    stageAdd(){
      const record = {
        baseProdCode:this.beanInfo.baseProdCode,
        instId: this.beanInfo.instId,
        prodType : "00" //基础产品
      }
      this.$nextTick(() => {
        this.$refs.modalForm.visible = true;
        this.$refs.modalForm.setBeanInfo('add',record,this.stageList.length);
      });
    },
    stageSubmit(){
      if(this.$refs.modalForm.operationType === 'add'){
        this.stageList.push(this.$refs.modalForm.beanInfo)
      }
      if(this.$refs.modalForm.operationType === 'edit'){
        this.stageList.splice(this.$refs.modalForm.index,0,this.$refs.modalForm.beanInfo)
        this.stageList.splice(this.$refs.modalForm.index+1,1)
      }
    },
  },
}
</script>

<style scoped>
.subtitle {
  width: 100%;
  font-size: 16px;
  margin-bottom: 10px;
  padding: 0 10px;
}

.sub-content-flex {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.sub-content-block {
  display: block;
  flex-wrap: wrap;
  width: 100%;
  padding: 0 10px;
}
.ant-table-wrapper,.ant-checkbox-group{
  width: 100%;
}
.ant-checkbox-wrapper{
  width: 32%;
}

</style>
